﻿using System;
using System.Linq;
using ProjetoComperio.DataLayer.Entities;
using ProjetoComperio.DataLayer.Infra;
using ProjetoComperio.Framework.Extensions;

namespace ProjetoComperio.BusinessLogicLayer
{
    public class EventBLL : ComperioDataObject, IDisposable
    {

        /// <summary>
        /// This method creates a new event
        /// </summary>
        public void Create(Event entity)
        {
            DbContext.Contributions.Add(entity);
            DbContext.SaveChanges();

        }

        /// <summary>
        /// This method edits a event
        /// </summary>
        /// <param name="entity"></param>
        public void Edit(Event eventEntity)
        {
            var originalEvent = this.RetrieveEvent(eventEntity.ContributionID);
            originalEvent.CopyValuesFrom(eventEntity);
            DbContext.SaveChanges();
        }

        /// <summary>
        /// This method retrieve a specific event
        /// </summary>
        /// <param name="eventID"></param>
        /// <returns></returns>
        public Event RetrieveEvent(Int32 contributionID)
        {
            return DbContext.Contributions.OfType<Event>().Where(eventEntity => eventEntity.ContributionID == contributionID).FirstOrDefault();
        }

        /// <summary>
        /// This method returns all events from db
        /// </summary>
        /// <param name="eventID"></param>
        /// <returns></returns>
        public IQueryable<Event> RetrieveEvents()
        {
            return DbContext.Contributions.OfType<Event>();
        }

        /// <summary>
        /// Retrieves all events related to the academicPersonID
        /// </summary>
        /// <param name="academicPersonID"></param>
        /// <returns></returns>
        public IQueryable<Event> RetrieveEvents(int academicPersonID)
        {
            return new ContributionBLL().RetrieveAcademicPersonContributions(academicPersonID).OfType<Event>();
        }

        /// <summary>
        /// This method returns the events registered on the last week
        /// </summary>
        /// <returns></returns>
        public IQueryable<Event> RetrieveRecentEvents()
        {
            var dateFromLastWeek = DateTime.Now.AddDays(-7);

            return DbContext.Contributions.OfType<Event>().Where(eventEntity => eventEntity.RegisterDate >= dateFromLastWeek);
        }

        public void Dispose()
        {
            DbContext.Dispose();
        }
    }
}
